
/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 *版权所有2002-2017原作者。
 *
 *根据Apache许可证2.0版许可（“许可证”）；
 *除非符合许可证的规定，否则您不得使用此文件。
 *您可以在以下网址获取许可证副本：
 *
 *https://www.apache.org/licenses/LICENSE-2.0
 *
 *除非适用法律要求或书面同意，软件
 *根据许可证进行的分发是在“按原样”的基础上进行的，
 *无任何明示或暗示的保证或条件。
 *有关管理权限的特定语言，请参阅许可证和
 *许可证下的限制。
 */

package org.springframework.format.support;

import java.util.Set;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.core.convert.support.ConversionServiceFactory;
import org.springframework.format.AnnotationFormatterFactory;
import org.springframework.format.Formatter;
import org.springframework.format.FormatterRegistrar;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.Parser;
import org.springframework.format.Printer;
import org.springframework.lang.Nullable;
import org.springframework.util.StringValueResolver;

/**
 * A factory providing convenient access to a {@code FormattingConversionService}
 * configured with converters and formatters for common types such as numbers and
 * datetimes.
 *
 * <p>Additional converters and formatters can be registered declaratively through
 * {@link #setConverters(Set)} and {@link #setFormatters(Set)}. Another option
 * is to register converters and formatters in code by implementing the
 * {@link FormatterRegistrar} interface. You can then configure provide the set
 * of registrars to use through {@link #setFormatterRegistrars(Set)}.
 *
 * <p>A good example for registering converters and formatters in code is
 * {@code JodaTimeFormatterRegistrar}, which registers a number of
 * date-related formatters and converters. For a more detailed list of cases
 * see {@link #setFormatterRegistrars(Set)}
 *
 * <p>Like all {@code FactoryBean} implementations, this class is suitable for
 * use when configuring a Spring application context using Spring {@code <beans>}
 * XML. When configuring the container with
 * {@link org.springframework.context.annotation.Configuration @Configuration}
 * classes, simply instantiate, configure and return the appropriate
 * {@code FormattingConversionService} object from a
 * {@link org.springframework.context.annotation.Bean @Bean} method.
 *
 * @author Keith Donald
 * @author Juergen Hoeller
 * @author Rossen Stoyanchev
 * @author Chris Beams
 * @since 3.0
 */
/**
 *提供方便访问｛@code FormattingConversionService｝的工厂
 *配置有用于常见类型的转换器和格式化程序，例如数字和
 *日期时间。
 *
 *<p>可以通过声明方式注册其他转换器和格式化程序
 *｛@link#setConverters（Set）｝和｛@link#setFormatters（Set）}。另一种选择
 *是通过实现
 *｛@link FormatterRegistrar｝接口。然后您可以配置提供集合
 *要通过｛@link#setFormatterRegistrars（Set）｝使用的注册器的数目。
 *
 *<p>在代码中注册转换器和格式化程序的一个好例子是
 *｛@code JodaTimeFormatterRegistrar｝，它注册了
 *与日期相关的格式化程序和转换器。有关更详细的案例列表
 *请参阅｛@link#setFormatterRegistrars（Set）｝
 *
 *<p>像所有{@code-FactoryBean}实现一样，这个类适用于
 *使用Spring｛@code＜beans＞｝配置Spring应用程序上下文时使用
 *XML。使用配置容器时
 *｛@link org.springframework.context.annation.Configuration@配置｝
 *类，只需实例化、配置并返回适当的
 *来自的｛@code FormattingConversionService｝对象
 *｛@link org.springframework.context.annation.Bean@Bean｝方法。
 *
 *@作者Keith Donald
 *@作者于尔根·霍勒
 *@作者Rossen Stoyanchev
 *@作者Chris Beams
 *@自3.0起
 */
public class FormattingConversionServiceFactoryBean
		implements FactoryBean<FormattingConversionService>, EmbeddedValueResolverAware, InitializingBean {

	@Nullable
	private Set<?> converters;

	@Nullable
	private Set<?> formatters;

	@Nullable
	private Set<FormatterRegistrar> formatterRegistrars;

	private boolean registerDefaultFormatters = true;

	@Nullable
	private StringValueResolver embeddedValueResolver;

	@Nullable
	private FormattingConversionService conversionService;


	/**
	 * Configure the set of custom converter objects that should be added.
	 * @param converters instances of any of the following:
	 * {@link org.springframework.core.convert.converter.Converter},
	 * {@link org.springframework.core.convert.converter.ConverterFactory},
	 * {@link org.springframework.core.convert.converter.GenericConverter}
	 */
	/**
	 *配置应添加的自定义转换器对象集。
	 *@param转换器以下任意一个的实例：
	 *｛@linkorg.springframework.core.coverter.coverter.converter｝，
	 *｛@link org.springframework.core.coverter.coverterFactory｝，
	 *｛@link org.springframework.core.coverter.converter.GenericConverter｝
	 */
	public void setConverters(Set<?> converters) {
		this.converters = converters;
	}

	/**
	 * Configure the set of custom formatter objects that should be added.
	 * @param formatters instances of {@link Formatter} or {@link AnnotationFormatterFactory}
	 */
	/**
	 *配置应添加的自定义格式化程序对象集。
	 *@param formatters｛@link Formatter｝或｛@linkAnnotationFormatterFactory｝的实例
	 */
	public void setFormatters(Set<?> formatters) {
		this.formatters = formatters;
	}

	/**
	 * <p>Configure the set of FormatterRegistrars to invoke to register
	 * Converters and Formatters in addition to those added declaratively
	 * via {@link #setConverters(Set)} and {@link #setFormatters(Set)}.
	 * <p>FormatterRegistrars are useful when registering multiple related
	 * converters and formatters for a formatting category, such as Date
	 * formatting. All types related needed to support the formatting
	 * category can be registered from one place.
	 * <p>FormatterRegistrars can also be used to register Formatters
	 * indexed under a specific field type different from its own &lt;T&gt;,
	 * or when registering a Formatter from a Printer/Parser pair.
	 * @see FormatterRegistry#addFormatterForFieldType(Class, Formatter)
	 * @see FormatterRegistry#addFormatterForFieldType(Class, Printer, Parser)
	 */
	/**
	 *<p>配置要调用以注册的FormatterRegistors集
	 *除了以声明方式添加的转换器和格式化程序之外
	 *通过{@link#setConverters（Set）}和{@link#setFormatters（Set）｝。
	 *<p>FormatterRegister在注册多个相关的
	 *格式化类别（如日期）的转换器和格式化程序
	 *格式化。支持格式化所需的所有相关类型
	 *类别可以在一个地方注册。
	 *＜p＞格式化程序注册器也可以用于注册格式化程序
	 *在不同于其自身&lt；T＞；，
	 *或者当从打印机/分析器对注册格式化程序时。
	 *@see FormatterRegistry#addFormatterForFieldType（类，格式化程序）
	 *@see FormatterRegistry#addFormatterForFieldType（类、打印机、分析器）
	 */
	public void setFormatterRegistrars(Set<FormatterRegistrar> formatterRegistrars) {
		this.formatterRegistrars = formatterRegistrars;
	}

	/**
	 * Indicate whether default formatters should be registered or not.
	 * <p>By default, built-in formatters are registered. This flag can be used
	 * to turn that off and rely on explicitly registered formatters only.
	 * @see #setFormatters(Set)
	 * @see #setFormatterRegistrars(Set)
	 */
	/**
	 *指示是否应注册默认格式化程序。
	 *<p>默认情况下，会注册内置的格式化程序。可以使用此标志
	 *关闭它并仅依赖于显式注册的格式化程序。
	 *@参见#setFormatters（设置）
	 *@参见#setFormatterRegistrars（集）
	 */
	public void setRegisterDefaultFormatters(boolean registerDefaultFormatters) {
		this.registerDefaultFormatters = registerDefaultFormatters;
	}

	@Override
	public void setEmbeddedValueResolver(StringValueResolver embeddedValueResolver) {
		this.embeddedValueResolver = embeddedValueResolver;
	}


	@Override
	public void afterPropertiesSet() {
		this.conversionService = new DefaultFormattingConversionService(this.embeddedValueResolver, this.registerDefaultFormatters);
		ConversionServiceFactory.registerConverters(this.converters, this.conversionService);
		registerFormatters(this.conversionService);
	}

	private void registerFormatters(FormattingConversionService conversionService) {
		if (this.formatters != null) {
			for (Object formatter : this.formatters) {
				if (formatter instanceof Formatter<?>) {
					conversionService.addFormatter((Formatter<?>) formatter);
				}
				else if (formatter instanceof AnnotationFormatterFactory<?>) {
					conversionService.addFormatterForFieldAnnotation((AnnotationFormatterFactory<?>) formatter);
				}
				else {
					throw new IllegalArgumentException(
							"Custom formatters must be implementations of Formatter or AnnotationFormatterFactory");
				}
			}
		}
		if (this.formatterRegistrars != null) {
			for (FormatterRegistrar registrar : this.formatterRegistrars) {
				registrar.registerFormatters(conversionService);
			}
		}
	}


	@Override
	@Nullable
	public FormattingConversionService getObject() {
		return this.conversionService;
	}

	@Override
	public Class<? extends FormattingConversionService> getObjectType() {
		return FormattingConversionService.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

}
